package cn.tedu.luban.worker.webapi.service.impl;

import cn.tedu.luban.account.service.IAccountService;
import cn.tedu.luban.attach.service.IAttachService;
import cn.tedu.luban.commons.enums.worker.AuditStatusEnum;

import cn.tedu.luban.commons.exception.LubanServiceException;
import cn.tedu.luban.commons.pojo.account.model.Account;
import cn.tedu.luban.commons.pojo.area.dto.WorkerAreaDTO;
import cn.tedu.luban.commons.pojo.attach.dto.AttachDTO;
import cn.tedu.luban.commons.pojo.attach.dto.AttachUpdateDTO;
import cn.tedu.luban.commons.pojo.attach.model.Attach;
import cn.tedu.luban.commons.pojo.category.dto.WorkerCategoryDTO;
import cn.tedu.luban.commons.pojo.worker.dto.IdCardDTO;
import cn.tedu.luban.commons.pojo.worker.dto.WorkerCreateDTO;
import cn.tedu.luban.commons.pojo.worker.model.Worker;
import cn.tedu.luban.commons.pojo.worker.model.WorkerArea;
import cn.tedu.luban.commons.pojo.worker.model.WorkerCategory;
import cn.tedu.luban.commons.pojo.worker.vo.*;
import cn.tedu.luban.commons.restful.ResponseCode;
import cn.tedu.luban.commons.utils.PropertiesUtils;
import cn.tedu.luban.worker.service.IWorkerService;
import cn.tedu.luban.worker.webapi.mapper.AuditMapper;
import cn.tedu.luban.worker.webapi.mapper.WorkerAreaMapper;
import cn.tedu.luban.worker.webapi.mapper.WorkerCategoryMapper;
import cn.tedu.luban.worker.webapi.mapper.WorkerMapper;
import cn.tedu.luban.worker.webapi.utils.SecurityContext;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class WorkerServiceImpl implements IWorkerService {


    @Autowired
    private WorkerMapper workerMapper;

    @Autowired
    private WorkerAreaMapper workerAreaMapper;

    @Autowired
    private WorkerCategoryMapper workerCategoryMapper;

    @Autowired
    private AuditMapper auditMapper;


    @DubboReference
    private IAttachService dubboAttachService;

    @DubboReference
    private IAccountService dubboAccountService;

    @Value("${app.business.type}")
    private Integer businessType;

    @Value("${url}")
    private String url;


    @Override
    @Transactional
    public Long createWorker(WorkerCreateDTO workerCreateDTO) {
        Long userId=SecurityContext.getUserId();
        workerCreateDTO.setUserId(userId);
        // 身份证验证没做,先写死
        IdCardVO idCardVO=new IdCardVO();
        idCardVO.setValid(true);
        idCardVO.setRealName("孙悟空");
        idCardVO.setCardNo("110101199910100011");
        // 判断验证结果
        if(idCardVO==null|| !idCardVO.isValid()){
            throw new LubanServiceException(ResponseCode.FORBIDDEN,"身份验证失败");
        }
        // 新增师傅
        Long id=saveWorker(userId,workerCreateDTO);

        // 新增区域和品类信息
        saveArea(userId,workerCreateDTO.getWorkerAreaList());
        saveCategory(userId,workerCreateDTO.getWorkerCategoryList());
        return id;
    }

    private void saveArea(Long userId,List<WorkerAreaDTO> workerAreaList){
        workerAreaMapper.delete(userId);
        if (!CollectionUtils.isEmpty(workerAreaList)) {
            workerAreaList.forEach(workerAreaDTO->{
                workerAreaDTO.setUserId(userId);
                WorkerArea workerArea=new WorkerArea();
                BeanUtils.copyProperties(workerAreaDTO,workerArea);
                workerArea.setGmtCreate(System.currentTimeMillis());
                workerArea.setGmtModified(System.currentTimeMillis());
                workerArea.setCreateUserId(userId);
                workerArea.setModifiedUserId(userId);
                workerArea.setCreateUserName("mock1");
                workerArea.setModifiedUserName("mock1");
                workerArea.setStatus(1);
                workerAreaMapper.insert(workerArea);
            });
        }
    }

    private void saveCategory(Long userId,List<WorkerCategoryDTO> workerCategoryList){
        workerCategoryMapper.delete(userId);
        if (!CollectionUtils.isEmpty(workerCategoryList)) {
            workerCategoryList.forEach(workerCategoryDTO->{
                workerCategoryDTO.setUserId(userId);
                WorkerCategory workerCategory=new WorkerCategory();
                BeanUtils.copyProperties(workerCategoryDTO,workerCategory);
                workerCategory.setGmtCreate(System.currentTimeMillis());
                workerCategory.setGmtModified(System.currentTimeMillis());
                workerCategory.setCreateUserId(userId);
                workerCategory.setModifiedUserId(userId);
                workerCategory.setCreateUserName("mock1");
                workerCategory.setModifiedUserName("mock1");
                workerCategory.setStatus(1);
                workerCategoryMapper.insert(workerCategory);
            });
        }
    }

    private Long saveWorker(Long userId, WorkerCreateDTO workerCreateDTO) {
        workerMapper.delete(userId);
        Worker worker=new Worker();
        BeanUtils.copyProperties(workerCreateDTO,worker);
        worker.setGmtCreate(System.currentTimeMillis());
        worker.setGmtModified(System.currentTimeMillis());
        worker.setCreateUserId(userId);
        worker.setModifiedUserId(userId);
        worker.setCreateUserName("mock1");
        worker.setModifiedUserName("mock1");
        worker.setStatus(1);
        worker.setAuditStatus(2);
        worker.setCertStatus(1);
        workerMapper.insert(worker);
        List<AttachUpdateDTO> attachUpdateDTOList=new ArrayList<>();
        for (IdCardDTO idCardDTO : workerCreateDTO.getAttachList()) {
            AttachUpdateDTO attachUpdateDTO=new AttachUpdateDTO();
            attachUpdateDTO.setId(idCardDTO.getId());
            attachUpdateDTO.setIsCover(idCardDTO.getType());
            attachUpdateDTO.setBusinessId(worker.getId().intValue());
            attachUpdateDTO.setBusinessType(businessType);
            attachUpdateDTOList.add(attachUpdateDTO);
        }
        dubboAttachService.batchUpdateAttachByIdList(attachUpdateDTOList);

        return worker.getId();
    }

    @Override
    public WorkerVO getWorkerDetail() {
        Long userId= SecurityContext.getUserId();
        Worker worker=workerMapper.getWorkerByWorkerId(userId);
        WorkerVO workerVO=new WorkerVO();
        BeanUtils.copyProperties(worker,workerVO);
        if (worker!=null){
            //查询区域
            List<WorkerArea> workerAreas=workerAreaMapper.getAreaByWorkerId(userId);
            if (!workerAreas.isEmpty()){
                workerVO.setAreaList(PropertiesUtils.copyListProperties(workerAreas,AreaVO.class));
            }
            //查询服务品类
            List<WorkerCategory> workerCategories=workerCategoryMapper.getWorkerCategoryByWorkerId(userId);
            if (!workerCategories.isEmpty()){
                workerVO.setCategoryList(PropertiesUtils.copyListProperties(workerCategories, CategoryVO.class));
            }
            //查询附件
            List<String> urls=getAttachList(worker.getId());
            workerVO.setAttachList(urls);
            //查询账户
            Account account=dubboAccountService.getAccountByUserId(userId);
            AccountVO accountVO=new AccountVO();
            accountVO.setTotalAmount(account!=null ? account.getTotalAmount() : 0L);
            workerVO.setAccountVO(accountVO);
            Integer auditStatus=worker.getAuditStatus();
            //审核未通过,赋值驳回原因
            if (AuditStatusEnum.REJECTED.getValue().equals(auditStatus)){
                workerVO.setRejectReason(auditMapper.getRejectReasonByUserId(userId));
            }

        }else{
            //用户首次登陆workerBO为空对象，设置auditStatus =3 表示未发起审核，未注册师傅。
            workerVO.setAuditStatus(AuditStatusEnum.UNCREATED.getValue());
        }

        return workerVO;
    }

    private List<String> getAttachList(Long id) {

        AttachDTO attachDTO=new AttachDTO();
        attachDTO.setBusinessId(id.intValue());
        attachDTO.setBusinessType(businessType);
        List<Attach> attachList=dubboAttachService.getAttachInfo(attachDTO);
        List<String> urls=new ArrayList<>();
        if(!attachList.isEmpty()){
            attachList.forEach(attach -> {
                urls.add(url+attach.getFileUuid());
            });
        }
        return urls;

    }

    // 百度验证代码:
    /*
    try {
        byte[] imgData = ByteStreamFromURL.getByteStreamFromURL(url);//
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        String param = "id_card_side=" + "front" + "&image=" + imgParam;
        log.info("url:{},token:{}", cardUrl, cartToken);
        String result = null;
        result = HttpUtil.post(cardUrl, cartToken, param);
        log.info("result={}", JSONObject.toJSONString(result));
        JSONObject jsonObject = JSON.parseObject(result);
        String wordsStr = JSONObject.toJSONString(jsonObject.get("words_result"));
        JSONObject wordsResultJson = JSONObject.parseObject(wordsStr);
        if (wordsResultJson.size() != 0) {

            String userNameStr = JSONObject.toJSONString(wordsResultJson.get("姓名"));
            JSONObject userNameJson = JSON.parseObject(userNameStr);
            String idCardStr = JSONObject.toJSONString(wordsResultJson.get("公民身份号码"));
            JSONObject idCardJson = JSON.parseObject(idCardStr);

            System.out.println(String.valueOf(idCardJson.get("words")));
            System.out.println(String.valueOf(userNameJson.get("words")));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }*/
}
